/***************************************************************************************************
Figure 7: Financial transactions and welfare gains by age group
a) Housing and equity transactions
b) Debt and deposits
***************************************************************************************************/
import delimited "$MyPath/Data/Micro Data/year_cohort", clear
rename *_sum *
merge m:1 year using "$MyPath/Save/kappa", keep(master matched) nogen
gen_transactions
replace debt_total = - debt_total



* Collapse into coarser age bins
gen age = year - b_year - 1
gen age_alt = round(age / 3) * 3
collapse (sum) nt_housing_total nt_equity_total debt_total deposits_total num_mean, by(age_alt year)
collapse (mean) nt_housing_total nt_equity_total debt_total deposits_total num_mean, by(age_alt)

* Per-capita
foreach v in nt_housing_total nt_equity_total debt_total deposits_total {
    replace `v' = `v' / num_mean
}

twoway ///
(line nt_housing_total age if inrange(age, 18, 80), lwidth(thick) color("$blue") lpattern(dash)) ///
(line nt_equity_total age if inrange(age, 18, 80), lwidth(thick) color("$green") lpattern(longdash_dot)) ///
, ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
xlabel(20[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-5 "-5K" 0 "0K" 5 "5K" 10 "10K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
xtitle("Current age", size(medlarge)) ///
ytitle("Net purchase", size(medlarge)) ///
legend(order(1 "Housing" 2 "Equity" ) size(medlarge) rows(1) symysize(6) symxsize(8) region(lwidth(vvthin)))
graph export "$MyPath/Figures/Figure7a.$suffix", replace


twoway ///
(line debt_total age if inrange(age, 18, 80) , lwidth(thick) color("$red") lpattern(shortdash)) ///
(line deposits_total age if inrange(age, 18, 80) , lwidth(thick) color("$yellow") lpattern(longdash)) ///
, ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
xlabel(20[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-150 "-150K" -100 "-100K" -50 "-50K" 0 "0K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
xtitle("Current age", size(medlarge)) ///
ytitle("Holdings", size(medlarge)) ///
legend(order(1 "Debt" 2 "Deposits" ) size(medlarge) rows(1) symysize(6) symxsize(8) region(lwidth(vvthin)))
graph export "$MyPath/Figures/Figure7b.$suffix", replace

/***************************************************************************************************
Figure 7: Financial transactions and welfare gains by age group
c) Welfare gains
***************************************************************************************************/
import delimited "$MyPath/Data/Micro Data/year_cohort", clear
rename *_sum *
merge m:1 year using "$MyPath/Save/kappa", keep(master matched) nogen
gen_transactions
merge m:1 year using "$MyPath/Save/prices", keep(master matched) nogen
gen_welfare, by(b_year)
* per capita
foreach v of varlist  welfare*  {
    replace `v' = `v' / num_mean
}
gen age = year - b_year - 1
save "$MyPath/save/bycohort_welfare_baseline", replace

* Collapse into coarser age bins for the graph
gen age_alt = round(age / 3) * 3
collapse (mean) welfare* [w =num_mean], by(age_alt)

* used for slides
twoway ///
(line welfare_total age if inrange(age, 3, 80), lwidth(thick) color(black)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(on order(1 "Total") size(medlarge) rows(1) symysize(6) symxsize(8) region(lwidth(vvthin)))  
graph export "$MyPath/Figures/Figure7c_slides.$suffix", replace

twoway ///
(line welfare_total age if inrange(age, 3, 80), lwidth(thick) color(black)) ///
(line welfare_housing age if inrange(age, 3, 80), lwidth(thick) color("$blue") lpattern(dash)) ///
(line welfare_debt age if inrange(age, 3, 80), lwidth(thick) color("$red") lpattern(shortdash)) ///
(line welfare_deposits age if inrange(age, 3, 80), lwidth(thick)  color("$yellow") lpattern(longdash)) ///
(line welfare_equity age if inrange(age, 3, 80), lwidth(thick)  color("$green") lpattern(longdash_dot)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) /// 
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge))  ///
legend(order(1 "Total" 2 "Housing" 3 "Debt" 4 "Deposits" 5 "Equity") size(medlarge) rows(1) symysize(6) symxsize(8) region(lwidth(vvthin)))
graph export "$MyPath/Figures/Figure7c.$suffix", replace

/***************************************************************************************************
Figure A3: Comparing our series for house-to-rent ratio with Jord` a et al. (2019)
c) Welfare gains across cohorts
***************************************************************************************************/
import delimited "$MyPath/Data/Micro Data/year_cohort", clear
rename *_sum *
merge m:1 year using "$MyPath/Save/kappa", keep(master matched) nogen
gen_transactions
merge m:1 year using "$MyPath/Save/prices", keep(master matched) nogen
replace PDh_shock = PDh_jst_shock
gen_welfare, by(b_year)
foreach v of varlist  welfare*  {
    replace `v' = `v' / num_mean
}
rename welfare* welfare*_jst
merge 1:1 b_year using "$MyPath/save/bycohort_welfare_baseline", nogen
* Collapse into coarser age bins
gen age_alt = round(age / 3) * 3
collapse (mean) welfare* [w = num_mean], by(age_alt)

twoway ///
(line welfare_total age if inrange(age, 3, 80), lwidth(thick) color(black)) ///
(line welfare_housing age if inrange(age, 3, 80), lwidth(thick) color("$blue") lpattern(dash)) ///
(line welfare_total_jst age if inrange(age, 3, 80), lwidth(medthick) color(black%50)) ///
(line welfare_housing_jst age if inrange(age, 3, 80), lwidth(medthick) color("$blue%50") lpattern(dash)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge))  ///
legend(order(1 "Total (Baseline)" 2 "Housing (Baseline)" 3 "Total (Jorda et al. 2019)" 4 "Housing (Jorda et al. 2019)") size(medlarge) rows(2) symysize(6) symxsize(8) region(lwidth(vvthin)))
graph export "$MyPath/Figures/FigureA3c.$suffix", replace

/***************************************************************************************************
Incomplete extension: compute covariance consumption with asset transactions
***************************************************************************************************/
/* survival rate */
import delimited "$MyPath/Data/Micro Data/year_cohort", clear
keep if year >= 1994
bys b_year (year): gen cumulative_survival_rate = num_mean / num_mean[1]
keep b_year year cumulative_survival_rate
tempfile temp_cumulative_survival_rate
save `temp_cumulative_survival_rate'

/* get betas of asset purchases on income (reduced form) */
drop _all
forval b_year = 1915(1)1991 {
    foreach v in debt_total deposits_total nt_equity_total nt_housing_total{
        import delimited "$MyPath/Data/Micro Data/incomplete_markets_income_`v'_`b_year'", clear
        gen asset = "`v'"
        tempfile temp `v'`b_year'
        save ``v'`b_year''
    }
}
drop _all
forval b_year = 1915(1)1991{
    foreach v in debt_total deposits_total nt_equity_total nt_housing_total{
        append using ``v'`b_year''
    }
}
replace asset = subinstr(asset, "_total", "", .)
replace asset = subinstr(asset, "nt_", "", .)
gen reference_year = max(1993, b_year + 18)
gen year = reference_year + horizon
keep b_year year horizon asset beta var
rename beta beta_reducedform
rename var var_income
tempfile temp_reducedform
save `temp_reducedform'

/* get betas of asset purchases on consumption instrumented by income (instrumental variable) */
drop _all
gen asset = "" 
forval b_year = 1915(1)1991{
    foreach v in debt_total deposits_total nt_equity_total nt_housing_total{
        local N = _N
        import delimited "$MyPath/Data/Micro Data/incomplete_markets_cons_iv_`v'_`b_year'", clear
        gen asset = "`v'"
        tempfile temp `v'`b_year'
        save ``v'`b_year''
    }
}
drop _all
forval b_year = 1915(1)1991{
    foreach v in debt_total deposits_total nt_equity_total nt_housing_total{
        append using ``v'`b_year''
    }
}
replace asset = subinstr(asset, "_total", "", .)
replace asset = subinstr(asset, "nt_", "", .)
gen reference_year = max(1993, b_year + 18)
gen year = reference_year + horizon
gen age = 1994 - b_year - 1
keep b_year year horizon asset beta var
rename var var_consumption
merge 1:1 b_year year asset using `temp_reducedform', keep(master matched) nogen
* check var is the same for every assets
gen var = (beta_reducedform / beta)^2 * var_income
egen temp = mean(var), by(b_year horizon)
assert abs(var - temp) <= 1e-3
replace var = temp
drop beta_reducedform var_income var_consumption temp
replace asset = "_" + asset
reshape wide beta, i(b_year year horizon var) j(asset) string
merge m:1 b_year year using `temp_cumulative_survival_rate', keep(master matched) nogen
gen cov_housing = beta_housing * var
gen cov_debt = beta_debt * var
gen cov_deposits = beta_deposits * var
gen cov_equity = beta_equity * var
save "$MyPath/save/bycohort_cov", replace

/***************************************************************************************************
Figure 10: Accounting for uninsurable labor income risk
***************************************************************************************************/
use "$MyPath/save/bycohort_cov", clear
merge m:1 year using "$MyPath/Save/prices", keep(master matched) nogen
gen cov_housing_shock = R0t_adhoc * cov_housing * PDh_shock * cumulative_survival_rate
gen cov_debt_shock = - R0t_adhoc * cov_debt * Qm_shock * cumulative_survival_rate
gen cov_deposits_shock =  R0t_adhoc * cov_deposits * Qd_shock * cumulative_survival_rate
gen cov_equity_shock = R0t_adhoc * cov_equity * PDe_shock * cumulative_survival_rate
gen cov_shock = cov_housing_shock + cov_debt_shock + cov_deposits_shock + cov_equity_shock
collapse (sum) cov*, by(b_year)
merge 1:1 b_year using "$MyPath/save/bycohort_welfare_baseline", nogen
* missing for b_year < 1915 but we know that zero in this face
foreach v of varlist cov*{
    replace cov_shock = 0 if b_year < 1915
}
* missing for b_year > 1991 so set remove them
drop if b_year > 1991
gen welfare_incomplete1 = welfare_total + 1 * cov_shock
gen welfare_incomplete2 = welfare_total + 2 * cov_shock
gen welfare_incomplete3 = welfare_total + 3 * cov_shock
keep b_year age num_mean welfare_* cov*
sort age
save "$MyPath/save/bycohort_welfare_incomplete", replace
drop if missing(welfare_incomplete1) 

* Collapse into coarser age bins for the graph
gen age_alt = round(age / 3) * 3
collapse (mean) cov_* welfare* [w =num_mean], by(age_alt)

twoway ///
(line cov_shock age if inrange(age, 3, 80), lwidth(thick) color(black)) ///
(line cov_housing_shock age if inrange(age, 3, 80), lwidth(thick) color("$blue") lpattern(dash)) ///
(line cov_debt_shock age if inrange(age, 3, 80),  lwidth(thick) color("$red") lpattern(shortdash)) ///
(line cov_deposits_shock age if inrange(age, 3, 80), lwidth(thick)  color("$yellow") lpattern(longdash)) ///
(line cov_equity_shock age if inrange(age, 3, 80),  lwidth(thick)  color("$green") lpattern(longdash_dot)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-4 "-4K" -2 "-2K" 0 "0K" 2 "2K" 4 "4K" 6 "6K" , labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
ytitle("Covariance", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(on order(1 "Total" 2 "Housing" 3 "Debt" 4 "Deposits" 5 "Equity") size(medlarge) rows(1) symysize(6) symxsize(8) region(lwidth(vvthin)))  
graph export "$MyPath/Figures/Figure10a.$suffix", replace

twoway ///
(line welfare_total age if inrange(age, 3, 80), color(black) lwidth(thick) ) ///
(line welfare_incomplete1 age if inrange(age, 3, 80), color(black%75) lwidth(medthick) lpattern(longdash)) ///
(line welfare_incomplete2 age if inrange(age, 3, 80), color(black%50) lwidth(medthick) lpattern(dash)) ///
(line welfare_incomplete3 age if inrange(age, 3, 80), color(black%25) lwidth(medthick) lpattern(shortdash)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(on order(1 "{&gamma} = 0" 2 "{&gamma} = 1" 3 "{&gamma} = 2" 4 "{&gamma} = 3") size(medlarge) rows(1) symysize(6) symxsize(8) region(lwidth(vvthin)))  
graph export "$MyPath/Figures/Figure10b.$suffix", replace



/***************************************************************************************************
Figure A9: Decomposing the effect of borrowing constraints on welfare gains
Figure 11: Accounting for borrowing constraints and collateral effects
b) Welfare gains with borrowing constraints
***************************************************************************************************/
import delimited "$MyPath/Data/Micro Data/welfare_cohort_xi_0", clear 
rename welfare* welfare*_0
tempfile temp0
save `temp0'
import delimited "$MyPath/Data/Micro Data/welfare_cohort_xi_5", clear 
rename welfare* welfare*_5
tempfile temp5
save `temp5'
import delimited "$MyPath/Data/Micro Data/welfare_cohort_xi_10", clear 
rename welfare* welfare*_10
merge 1:1 b_year using `temp0', nogen
merge 1:1 b_year using `temp5', nogen
gen age = 1994 - b_year - 1
merge 1:1 age using "$MyPath/save/bycohort_welfare_baseline", nogen
foreach v of varlist  welfare*_0 welfare*_5 welfare*_10 {
    replace `v' = `v' / num_mean
}
gen welfare_discountrate_10 = (welfare_total_10 - welfare_collateral_10) - welfare_total_0
gen welfare_discountrate_5 = (welfare_total_5 - welfare_collateral_5) - welfare_total_0
save "$MyPath/save/bycohort_welfare_collateral", replace


* Collapse into coarser age bins for the graph
gen age_alt = round(age / 3) * 3
collapse (mean) welfare* [w =num_mean], by(age_alt)


/* Figure A9 */
twoway ///
(line welfare_total age if inrange(age, 3, 80), color(black) lwidth(thick) ) ///
(line welfare_discountrate_10 age if inrange(age, 3, 80), color(black%50) lwidth(medthick) lpattern(shortdash)) ///
(line welfare_collateral_10 age if inrange(age, 3, 80), color(black%25) lwidth(medthick) lpattern(longdash)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(on order(1 "Baseline"  2 "Discount rate channel" 3 "Collateral channel" ) size(medlarge) rows(1) symysize(6) symxsize(8) region(lwidth(vvthin)))
graph export "$MyPath/Figures/FigureA9.$suffix", replace

/* Figure 11b */
replace welfare_total_5 = welfare_total + welfare_discountrate_5 + welfare_collateral_5
replace welfare_total_10 = welfare_total + welfare_discountrate_10 + welfare_collateral_10
twoway ///
(line welfare_total age if inrange(age, 3, 80), color(black) lwidth(thick) ) ///
(line welfare_total_5 age if inrange(age, 3, 80), color(black%50) lwidth(medthick) lpattern(longdash)) ///
(line welfare_total_10 age if inrange(age, 3, 80), color(black%25) lwidth(medthick) lpattern(shortdash)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(on order(1 "{&xi} = 0"  2 "{&xi} = 0.005" 3 "{&xi} = 0.01") size(medlarge) rows(1) symysize(6) symxsize(8) region(lwidth(vvthin)))
graph export "$MyPath/Figures/Figure11b.$suffix", replace

/***************************************************************************************************
Create dataset with predicted transactions at time 1994-1996 (used for second-order effects)
***************************************************************************************************/
import delimited "$MyPath/Data/Micro Data/year_cohort", clear
rename *_sum *
keep if year >= 1994
merge m:1 year using "$MyPath/Save/kappa", keep(master matched) nogen
gen_transactions
gen age = year - b_year - 1
drop if age > 83
foreach v of varlist nt_housing_total debt_total deposits_total nt_equity_total{
    replace `v' = `v' / num_mean
}
preserve
* compute average transactions at the start of the sample
keep if inrange(year, 1994, 1998)
collapse (mean) nt_housing_total debt_total deposits_total nt_equity_total, by(age)
foreach v of varlist nt_housing_total debt_total deposits_total nt_equity_total{
    rename `v'  `v'0
}
tempfile temp0
save `temp0'
restore
merge m:1 age using `temp0', keep(master matched) nogen
merge m:1 year using "$MyPath/save/prices", keep(master matched) nogen
* counterfactual average transactions
gen nt_housing_total_counterfactual = exp(0.01 * (year - 1994)) * PDh / PDh0 * nt_housing_total0
gen debt_total_counterfactual = exp(0.01 * (year - 1994)) * Qm / Qm0 * debt_total0
gen deposits_total_counterfactual = exp(0.01 * (year - 1994)) * Qd / Qd0 * deposits_total0
gen nt_equity_total_counterfactual = exp(0.01 * (year - 1994)) * PDe / PDe0 * nt_equity_total0
sort year age
gen scale_housing = (1 + nt_housing_total_counterfactual / nt_housing_total)  / 2
gen scale_debt = (1 + debt_total_counterfactual / debt_total) / 2 
gen scale_deposits = (1 + deposits_total_counterfactual / deposits_total) / 2 
gen scale_equity = (1 + nt_equity_total_counterfactual / nt_equity_total) / 2 
save "$MyPath/save/bycohort_secondorder_transactions", replace

/***************************************************************************************************
Figure 12: Accounting for second-order effects
***************************************************************************************************/
use "$MyPath/save/bycohort_secondorder_transactions", clear
gen age_alt = round(age / 3) * 3
* the transactions correspond to transactions per capita
collapse (mean) *_total *_total_counterfactual [w = num_mean], by(age_alt year)
collapse (mean) *_total *_total_counterfactual, by(age_alt)

twoway ///
(line nt_housing_total age if inrange(age, 18, 80), lwidth(thick) color("$blue") lpattern(dash)) ///
(line nt_housing_total_counterfactual age if inrange(age, 18, 80), lwidth(thick) color("$blue%40") lpattern(dash)) ///
(line nt_equity_total age if inrange(age, 18, 80), lwidth(thick) color("$green") lpattern(longdash_dot)) ///
(line nt_equity_total_counterfactual age if inrange(age, 18, 80), lwidth(thick) color("$green%40") lpattern(longdash_dot)) ///
, ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
xlabel(20[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-5 "-5K" 0 "0K" 5 "5K" 10 "10K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
ytitle("Net purchase", size(medlarge))  xtitle("Current age", size(medlarge)) ///
legend(order(1 "Housing" 2 "Housing (counterfactual)"  3  "Equity" 4 "Equity (counterfactual)") size(medlarge) rows(2))
graph export "$MyPath/Figures/Figure12a.$suffix", replace

replace debt_total = - debt_total
replace debt_total_counterfactual = - debt_total_counterfactual

twoway ///
(line debt_total age if inrange(age, 18, 80), lwidth(thick) color("$red") lpattern(shortdash)) ///
(line debt_total_counterfactual age if inrange(age, 18, 80), lwidth(thick) color("$red%40") lpattern(shortdash)) ///
(line deposits_total age if inrange(age, 18, 80), lwidth(thick) color("$yellow") lpattern(longdash)) ///
(line deposits_total_counterfactual age if inrange(age, 18, 80), lwidth(thick) color("$yellow%40") lpattern(longdash)) ///
, ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
xlabel(20[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-150 "-150K" -100 "-100K" -50 "-50K" 0 "0K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
ytitle("Holdings", size(medlarge))  xtitle("Current age", size(medlarge)) ///
legend(order(1 "Debt"   2 "Debt (counterfactual)" 3 "Deposits" 4 "Deposits (counterfactual)" ) size(medlarge) rows(2))
graph export "$MyPath/Figures/Figure12b.$suffix", replace

/***************************************************************************************************
Figure 12c and 12d
***************************************************************************************************/
import delimited "$MyPath/Data/Micro Data/year_cohort", clear
rename *_sum *
merge m:1 year using "$MyPath/Save/kappa", keep(master matched) nogen
gen_transactions
gen age = year - b_year - 1
merge m:1 age year using "$MyPath/save/bycohort_secondorder_transactions", keep(master matched) nogen keepusing(scale*)
replace scale_housing = 1 if missing(scale_housing)
replace scale_debt = 1 if missing(scale_debt)
replace scale_deposits = 1 if missing(scale_deposits)
replace scale_equity = 1 if missing(scale_equity)

* replace all price shocks
merge m:1 year using "$MyPath/Save/prices", keep(master matched) nogen
replace PDh_shock = PDh_shock * scale_housing
replace Qd_shock = Qd_shock * scale_deposits
replace Qm_shock = Qm_shock * scale_debt
replace PDe_shock = PDe_shock * scale_equity
replace R0t_adhoc = 1.025^(-(year - 1994))
gen_welfare, by(b_year)
foreach v of varlist  welfare*  {
    replace `v' = `v' / num_mean
}
rename welfare*  welfare*_2nd
save "$MyPath/save/bycohort_welfare_secondorder", replace


merge 1:1 age using "$MyPath/save/bycohort_welfare_baseline", keep(master matched) nogen

* Collapse into coarser age bins for the graph
gen age_alt = round(age / 3) * 3
collapse (mean) welfare* [w =num_mean], by(age_alt)

twoway ///
(line welfare_total age if inrange(age, 3, 80), lwidth(thick) color(black)) ///
(line welfare_total_2nd age if inrange(age, 3, 80), lwidth(thick) lpattern(dash) color(black%50)) ///
, ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(order(1 "First-order approximation" 2 "Second-order approximation") size(medlarge) rows(2) symysize(6) symxsize(8) region(lwidth(vvthin)))
graph export "$MyPath/Figures/Figure12c.$suffix", replace

twoway ///
(line welfare_housing age if inrange(age, 3, 80), lwidth(thick) color("$blue") lpattern(dash)) ///
(line welfare_debt age if inrange(age, 3, 80), lwidth(thick) color("$red") lpattern(shortdash)) ///
(line welfare_deposits age if inrange(age, 3, 80), lwidth(thick)  color("$yellow") lpattern(longdash)) ///
(line welfare_equity age if inrange(age, 3, 80), lwidth(thick)  color("$green") lpattern(longdash_dot)) ///
(line welfare_housing_2nd age if inrange(age, 3, 80), lwidth(medthick) color("$blue%40") lpattern(dash)) ///
(line welfare_debt_2nd age if inrange(age, 3, 80), lwidth(medthick) color("$red%40") lpattern(shortdash)) ///
(line welfare_deposits_2nd age if inrange(age, 3, 80), lwidth(medthick)  color("$yellow%40") lpattern(longdash)) ///
(line welfare_equity_2nd age if inrange(age, 3, 80), lwidth(medthick)  color("$green%40") lpattern(longdash_dot)) ///
, ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  ///
xtitle("Initial age", size(medlarge)) ///
legend(order(1 "Housing (1rst)" 2 "Debt (1rst)" 3 "Deposits (1rst)" 4 "Equity (1rst)" 5 "Housing (2nd)" 6 "Debt (2nd)" 7 "Deposits (2nd)" 8 "Equity (2nd)") size(medsmall) rows(2) symysize(6) symxsize(8) region(lwidth(vvthin)))
graph export "$MyPath/Figures/Figure12d.$suffix", replace

/***************************************************************************************************
Extrapolate extension:  Create dataset with synthetic prices
a) Extrapolated house prices
***************************************************************************************************/
use "$MyPath/Save/prices", clear
set obs `=_N + 2100 - 2019'
replace year = year[_n-1] + 1 if missing(year)
foreach v of varlist PDh0 PDe0 Qd0 Qm0{
    replace `v' = `v'[_n-1] if missing(`v')
}
replace R0t_adhoc = 1.05^(-(year - 1994))
local i = 0
foreach phi in 00 90 95 98{
    foreach v of varlist PDh PDe Qd Qm{
        gen `v'_`phi' = `v'
        sum `v' if inrange(year, 2016, 2019)
        local m = r(mean)
        replace `v'_`phi' = `v'0 * (`m' / `v'0)^((`phi'/100)^(year - 2019)) if year > 2019
        gen `v'_`phi'_shock = (`v'_`phi' - `v'0) / `v'_`phi'
    }
}
save "$MyPath/Save/prices_synthetic", replace

*/ Figure 13: Accounting for extrapolated changes in asset prices beyond 2019 a) Extrapolated house prices */
replace rentpricescpissb = rentpricescpissb / cpi
replace rentpricescpissb = rentpricescpissb[_n-1] * 1.01 if missing(rentpricescpissb)
gen Ph0 = rentpricescpissb * PDh0
gen Ph_00 = rentpricescpissb * PDh_00
gen Ph_90 = rentpricescpissb * PDh_90
gen Ph_95 = rentpricescpissb * PDh_95
gen Ph_98 = rentpricescpissb * PDh_98

sum Ph0 if year == 1980
foreach v of varlist Ph0 Ph_00 Ph_90 Ph_95 Ph_98{
    replace `v' = `v' / r(mean)
}

keep if year <= 2039
twoway ///
(line Ph0 year, connect(l) lwidth(thick) color("black") lpattern(dash_dot )) ///
(line Ph_0 year, connect(l)  lwidth(thick) color("black") lpattern(solid)) ///
(line Ph_90 year, connect(l)  lwidth(medthick) color(black%75) lpattern(longdash)) ///
(line Ph_95 year, connect(l)  lwidth(medthick) color(black%50) lpattern(dash)) ///
(line Ph_98 year, connect(l)  lwidth(medthick) color(black%25) lpattern(shortdash)) ///
, ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(0 1 2 3 4 5, labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0))  ///
xscale(range(1980 2042)) ///
yscale(range(0 5)) ///
xtitle("Year", size(medlarge)) ///
ytitle("(1980 = 1)", size(medlarge)) ///
legend(order(2 "{&phi} = 0" 3 "{&phi} = 0.9" 4 "{&phi} = 0.95" 5 "{&phi} = 0.98") size(medlarge) rows(1)) ///
text(`=Ph_98[_N-5]-0.1' 2039.5 "P{subscript:H,t}", size(medium) color("black") placement(east)) ///
text(`=Ph_00[_N-5]-0.18' 2036.4 "PD{subscript:H} x D{subscript:H,t}", size(medium) color("black") placement(east)) ///
text(`=Ph_00[_N-5]' 2036.7 "—" , size(large) color("black") placement(east))
graph export "$MyPath/Figures/Figure13a.$suffix", replace

/***************************************************************************************************
Extrapolate extension:  Create dataset with synthetic population number and transactions
***************************************************************************************************/
/* Part 1 :  Create synthetic population mass */
import delimited "$MyPath/Data/Micro Data/year_cohort", clear
gen age = year - b_year - 1
keep if age <= 100
tsset b_year year
gen prob_survival = F.num_mean / num_mean
collapse (mean) prob_survival, by(age)
tempfile temp
save `temp'


import delimited "$MyPath/Data/Micro Data/year_cohort", clear
keep if b_year >= 1894
keep b_year year num_mean
tempfile temp1
save  `temp1'

* create rectangular dataset with b_year between 1894 and 2100 and year between 1994 and 2100
clear
set obs `=2100 - 1894 + 1'
gen b_year = 1894 + _n - 1
tempfile b_year
save `b_year'
clear
set obs 108
gen year = 1993 + _n - 1 if _n <= 108
cross using `b_year'

* add num_mean from existing b_year year
merge 1:1 b_year year using `temp1', nogen
gen synthetic = missing(num_mean)
* create num_mean in future cohorts or future years
* first create initial num_mean of future cohorts assuming zero population growth
egen temp = max(num_mean), by(b_year)
* last cohort
sum temp if b_year == 2001
bys b_year (year): replace num_mean = r(mean) if _n == 1 & missing(num_mean)
drop temp
* then extrapolate num_mean using probability of survival by age
gen age = year - b_year - 1
merge m:1 age using `temp', nogen
replace prob_survival = 1 if age <= 18
replace prob_survival = 0 if age >= 100 
bys b_year (year): replace num_mean = num_mean[_n-1] * prob_survival[_n-1] if missing(num_mean)
drop prob_survival
tempfile temp_synthetic_population
save `temp_synthetic_population'


/* Part 2 : Synthetic transactions */
import delimited "$MyPath/Data/Micro Data/year_cohort", clear
rename *_sum *
merge m:1 year using "$MyPath/Save/kappa", keep(master matched) nogen
gen_transactions
gen debt_gross = debt + debt_pb
foreach v of varlist debt_gross *_total {
    replace `v' = `v' / num_mean
}
gen age = year - b_year - 1
keep year b_year age debt_gross *_total 
tempfile temp_synthetic_transactions
save `temp_synthetic_transactions'

keep if inrange(age, 18, 100)
merge m:1 year using "$MyPath/Save/prices", keep(master matched) nogen
replace nt_housing_total = nt_housing_total / (PDh / PDh0 * exp(0.01 * (year - 1994)))
replace nt_equity_total = nt_equity_total / (PDe / PDe0 * exp(0.01 * (year - 1994)))
replace deposits_total = deposits_total / (Qd / Qd0 * exp(0.01 * (year - 1994)))
replace debt_total = debt_total / (Qm / Qm0 * exp(0.01 * (year - 1994)))
replace debt_gross = debt_gross / (Qm / Qm0 * exp(0.01 * (year - 1994)))
collapse (mean) debt_gross *_total, by(age)
tempfile temp_ageeffect
save `temp_ageeffect'

use `temp_synthetic_population', clear
merge 1:1 b_year year using `temp_synthetic_transactions', nogen
assert !missing(age)
merge m:1 age using `temp_ageeffect', update
drop age
foreach v of varlist debt_gross *_total {
    replace `v' = `v' * num_mean
}
tsset b_year year
save "$MyPath/save/bycohort_synthetic", replace

/***************************************************************************************************
Figure 13b: Accounting for extrapolated changes in asset prices beyond 2019 ; Welfare gains across cohorts
Figure A12: Welfare gain depending on the behavior of asset prices in the future, asset class by
asset class
***************************************************************************************************/
use "$MyPath/Save/bycohort_synthetic", clear
merge m:1 year using "$MyPath/Save/prices_synthetic", keep(master matched) nogen
* What I should scale is the amount of transactions, but turns out to be equivalent (and simpler) to scale the price shocks instead given the formula for welfare gains
foreach v in PDh Qm Qd PDe{
    replace `v'_shock = `v'_00_shock * `v'_00 / `v'0 * exp(0.01 * (year - 1994)) if year > 2019
}    
gen_welfare, by(b_year)
gen phi = "0"
tempfile temp
save `temp'

use "$MyPath/Save/bycohort_synthetic", clear
merge m:1 year using "$MyPath/Save/prices_synthetic", keep(master matched) nogen
foreach v in PDh Qm Qd PDe{
    replace `v'_shock = `v'_90_shock * `v'_90 / `v'0 * exp(0.01 * (year - 1994)) if year > 2019
}    
gen_welfare, by(b_year)
gen phi = "90"
tempfile temp1
save `temp1'

use "$MyPath/Save/bycohort_synthetic", clear
merge m:1 year using "$MyPath/Save/prices_synthetic", keep(master matched) nogen
foreach v in PDh Qm Qd PDe{
    replace `v'_shock = `v'_95_shock * `v'_95 / `v'0 * exp(0.01 * (year - 1994)) if year > 2019
}    
gen_welfare, by(b_year)
gen phi = "95"
tempfile temp2
save `temp2'

use "$MyPath/Save/bycohort_synthetic", clear
merge m:1 year using "$MyPath/Save/prices_synthetic", keep(master matched) nogen

foreach v in PDh Qm Qd PDe{
    replace `v'_shock = `v'_98_shock * `v'_98 / `v'0 * exp(0.01 * (year - 1994)) if year > 2019
}    
gen_welfare, by(b_year)
gen phi = "98"
append using `temp'
append using `temp1'
append using `temp2'
foreach v of varlist welfare*  {
    replace `v' = `v' / num_mean
}
keep year b_year num_mean  phi welfare*
gather welfare*
replace variable = variable + "_" + phi
drop phi
spread variable value
gen age = year - b_year - 1
save "$MyPath/save/bycohort_welfare_untruncated", replace

gen age_alt = round(age / 3) * 3
collapse (mean) welfare* [w = num_mean], by(age_alt)

sort age
twoway ///
(line welfare_total_0 age if inrange(age, 3, 80),  lwidth(thick) yaxis(1) color(black)) ///
(line welfare_total_90 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(longdash) yaxis(1) color(black%75)) ///
(line welfare_total_95 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(dash) yaxis(1) color(black%50)) ///
(line welfare_total_98 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(shortdash) yaxis(1) color(black%25)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) /// 
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(order(1 "{&phi} = 0" 2 "{&phi} = 0.9" 3 "{&phi} = 0.95" 4 "{&phi} = 0.98") size(medlarge) rows(1))
graph export "$MyPath/Figures/Figure13b.$suffix", replace

twoway ///
(line welfare_housing_0 age if inrange(age, 3, 80),  lwidth(thick) yaxis(1) color("$blue")) ///
(line welfare_housing_90 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(dash) yaxis(1) color("$blue%75")) ///
(line welfare_housing_95 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(shortdash) yaxis(1) color("$blue%50")) ///
(line welfare_housing_98 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(longdash) yaxis(1) color("$blue%25")) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) /// 
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(order(1 "{&phi} = 0" 2 "{&phi} = 0.9" 3 "{&phi} = 0.95" 4 "{&phi} = 0.98") size(medlarge) rows(1))
graph export "$MyPath/Figures/FigureA12a.$suffix", replace

twoway ///
(line welfare_equity_0 age if inrange(age, 3, 80),  lwidth(thick) yaxis(1) color("$green")) ///
(line welfare_equity_90 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(dash) yaxis(1) color("$green%75")) ///
(line welfare_equity_95 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(shortdash) yaxis(1) color("$green%50")) ///
(line welfare_equity_98 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(longdash) yaxis(1) color("$green%25")) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) /// 
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(order(1 "{&phi} = 0" 2 "{&phi} = 0.9" 3 "{&phi} = 0.95" 4 "{&phi} = 0.98") size(medlarge) rows(1))
graph export "$MyPath/Figures/FigureA12b.$suffix", replace

twoway ///
(line welfare_debt_0 age if inrange(age, 3, 80),  lwidth(thick) yaxis(1) color("$red")) ///
(line welfare_debt_90 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(dash) yaxis(1) color("$red%75")) ///
(line welfare_debt_95 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(shortdash) yaxis(1) color("$red%50")) ///
(line welfare_debt_98 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(longdash) yaxis(1) color("$red%25")) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) /// 
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(order(1 "{&phi} = 0" 2 "{&phi} = 0.9" 3 "{&phi} = 0.95" 4 "{&phi} = 0.98") size(medlarge) rows(1))
graph export "$MyPath/Figures/FigureA12c.$suffix", replace

twoway ///
(line welfare_deposits_0 age if inrange(age, 3, 80),  lwidth(thick) yaxis(1) color("$yellow")) ///
(line welfare_deposits_90 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(dash) yaxis(1) color("$yellow%75")) ///
(line welfare_deposits_95 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(shortdash) yaxis(1) color("$yellow%50")) ///
(line welfare_deposits_98 age if inrange(age, 3, 80),  lwidth(medthick) lpattern(longdash) yaxis(1) color("$yellow%25")) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) /// 
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(order(1 "{&phi} = 0" 2 "{&phi} = 0.9" 3 "{&phi} = 0.95" 4 "{&phi} = 0.98") size(medlarge) rows(1))
graph export "$MyPath/Figures/FigureA12d.$suffix", replace

/***************************************************************************************************
Do final extension that combines all existing extensions
***************************************************************************************************/
/* Part 1: extend covariance patterns */
use "$MyPath/save/bycohort_cov", clear
foreach v of varlist cov_housing cov_debt cov_deposits cov_equity{
    bys b_year (year): gen `v'change = (`v'[_N]/ `v'[_N-5])^(1/5) 
    bys b_year (year): replace `v'change = 0 if `v'[_N] *  `v'[_N-5] < 0
    bys b_year (year): replace `v'change = 0 if missing(`v'[_N-5])
}
keep b_year year cov*
tempfile temp
save `temp'

use "$MyPath/save/bycohort_synthetic", clear
keep if year >= 1994
keep year b_year num_mean
gen age = year - b_year + 1
merge 1:1 b_year year using `temp'
gen synthetic = _merge != 3
drop _merge
foreach v of varlist cov_housing cov_debt cov_deposits cov_equity{
    bys b_year (year): replace `v'change = `v'change[_n-1] if missing(`v'change)
    bys b_year (year): replace `v' = `v'[_n-1] * `v'change[_n-1] if missing(`v')
}
drop *change
sort b_year year
tempfile temp_cov_oldcohort
save `temp_cov_oldcohort'

* covariance pattern of unborn cohorts
keep if inrange(b_year, 1970, 1974)
collapse (mean) cov*, by(age)
tempfile temp_cov_newcohort
save `temp_cov_newcohort'

use `temp_cov_oldcohort', clear
foreach v of varlist cov_housing cov_debt cov_deposits cov_equity{
    * do that so that does not get updated
    replace `v' = 0 if synthetic == 1 & missing(`v') 
    replace `v' = . if synthetic == 1 & b_year > 1974
}
merge m:1 age using `temp_cov_newcohort', update nogen
foreach v of varlist cov_housing cov_debt cov_deposits cov_equity{
    replace `v' = `v' * num_mean
}
keep year b_year cov*
tempfile temp_cov_synthetic
save `temp_cov_synthetic'


/* Part 2: Combine */
use "$MyPath/save/bycohort_synthetic", clear
merge m:1 year using "$MyPath/Save/prices_synthetic", keep(master matched) nogen
foreach v in PDh Qm Qd PDe{
    replace `v'_shock = `v'_90_shock * `v'_90 / `v'0 * exp(0.01 * (year - 1994)) if year > 2019
}
merge 1:1 b_year year using `temp_cov_synthetic', keep(master matched) nogen
* do second order
foreach v of varlist nt_housing_total debt_total deposits_total nt_equity_total {
    replace `v' = `v' / num_mean
}
gen age = year - b_year - 1
preserve
keep if inrange(year, 1994, 1998)
collapse (mean) nt_housing_total debt_total deposits_total nt_equity_total, by(age)
foreach v of varlist nt_housing_total debt_total deposits_total nt_equity_total{
    rename `v'  `v'0
}
tempfile temp1
save `temp1'
restore
merge m:1 age using `temp1', keep(master matched) nogen
gen scale_housing = clip(0.3, (1 + nt_housing_total0 * PDh / PDh0 * exp(0.01 * (year - 1994)) / nt_housing_total)  / 2, 3) if !missing(nt_housing_total0)
gen scale_debt = clip(0.3, (1 + debt_total0 * Qm / Qm0 * exp(0.01 * (year - 1994)) / debt_total) / 2, 3)  if !missing(debt_total0)
gen scale_deposits = clip(0.3, (1 + deposits_total0 * Qd / Qd0 * exp(0.01 * (year - 1994)) / deposits_total) / 2, 3)  if !missing(deposits_total0)
gen scale_equity = clip(0.3, (1 + nt_equity_total0 * PDe / PDe0 * exp(0.01 * (year - 1994)) / nt_equity_total) / 2, 3)  if !missing(nt_equity_total0)
foreach v of varlist nt_housing_total debt_total deposits_total nt_equity_total {
    replace `v' = `v' * num_mean
}
keep if year >= 1994
gen ltv = clip(debt_gross / housing_total, 0, 1)
replace ltv = 0 if missing(ltv)
gen temp = 2 * 0.01 * clip(ltv, 0, 1)^2
bys b_year (year): gen cumtemp = sum(temp * (year > 1994))
gen R0t = 1.025^(1994-year) * exp(-cumtemp)
egen welfare_housing = sum(R0t * (-nt_housing_total + cov_housing) * scale_housing * PDh_shock * (year >= 1994)), by(b_year)
egen welfare_deposits = sum(R0t * (-deposits_total + cov_deposits) * scale_deposits * Qd_shock * (year >= 1994)), by(b_year)
egen welfare_debt = sum(R0t * (debt_total - cov_debt) * scale_debt * Qm_shock * (year >= 1994)), by(b_year)
egen welfare_equity = sum(R0t * (-nt_equity_total + cov_equity) * scale_equity * PDe_shock * (year >= 1994)), by(b_year)
egen welfare_collateral = sum(R0t * (ltv * debt_gross + ltv * cov_debt) * clip(scale_debt / scale_housing, 0.5, 1.5) * 0.01 * PDh_shock * (year >= 1994)), by(b_year)
gen welfare_total = welfare_housing + welfare_deposits + welfare_debt + welfare_equity + welfare_collateral
keep if year == 1994
foreach v of varlist  welfare*  {
    replace `v' = `v' / num_mean
}
rename welfare_total welfare_total_combine
save "$MyPath/save/bycohort_welfare_combine", replace

/***************************************************************************************************
Table 3: Welfare gains across cohorts: generalizations of our baseline approach
***************************************************************************************************/
tempfile postfile
tempname postname

postfile `postname' str200 label m m1 m2 m3 m4 using `postfile', replace

use "$MyPath/save/bycohort_welfare_baseline", clear
sum welfare_total [w = num_mean] if inrange(age, 0, 80)
local m_baseline = r(mean)
sum welfare_total [w = num_mean] if inrange(age, 0, 19)
local m1_baseline = r(mean)
sum welfare_total [w = num_mean] if inrange(age, 20, 39)
local m2_baseline = r(mean)
sum welfare_total [w = num_mean] if inrange(age, 40, 59)
local m3_baseline = r(mean)
sum welfare_total [w = num_mean] if inrange(age, 60, 80)
local m4_baseline = r(mean)
post `postname' ("Baseline") (`m_baseline') (`m1_baseline') (`m2_baseline') (`m3_baseline') (`m4_baseline') 

* Number used in Introduction and 3.2 Redistribution across cohorts
tempname handle
file open `handle' using "$MyPath/Numbers/wf_cohort_15.tex", write replace
sum welfare_total [w = num_mean] if age <= 15
file write `handle'  "-\\$`: di  %9.0fc abs(r(mean))',000"
file close `handle'

tempname handle
file open `handle' using "$MyPath/Numbers/wf_cohort_30.tex", write replace
sum welfare_total [w = num_mean] if age >= 30
file write `handle'  "\\$`: di  %9.0fc r(mean)',000"
file close `handle'



use "$MyPath/save/bycohort_welfare_incomplete", clear
sum welfare_incomplete1 [w = num_mean] if inrange(age, 0, 80)
local m = r(mean)
sum welfare_incomplete1 [w = num_mean] if inrange(age, 0, 19)
local m1 = r(mean)
sum welfare_incomplete1 [w = num_mean] if inrange(age, 20, 39)
local m2 = r(mean)
sum welfare_incomplete1 [w = num_mean] if inrange(age, 40, 59)
local m3 = r(mean)
sum welfare_incomplete1 [w = num_mean] if inrange(age, 60, 80)
local m4 = r(mean)
post `postname' ("\noalign{\vskip 1.5mm} Additional effect of \dots &&&&&\\ \enspace Uninsurable income risk") (`m'-`m_baseline') (`m1'-`m1_baseline') (`m2'-`m2_baseline') (`m3'-`m3_baseline') (`m4'-`m4_baseline')


* Numbers used in Section 4.1: Uninsurable income risk
tempname handle
file open `handle' using "$MyPath/Numbers/welfare20_total.tex", write replace
sum welfare_total if inrange(age, 8, 12)
file write `handle' "-\\$`:di %2.0fc `=abs(r(mean))''"
file close `handle'

tempname handle
file open `handle' using "$MyPath/Numbers/welfare20_1.tex", write replace
sum welfare_incomplete1 if inrange(age, 8, 12)
file write `handle' "-\\$`:di %2.0fc `=abs(r(mean))''"
file close `handle'

tempname handle
file open `handle' using "$MyPath/Numbers/welfare20_3.tex", write replace
sum welfare_incomplete3 if inrange(age, 8, 12)
file write `handle' "-\\$`:di %2.0fc `=abs(r(mean))''"
file close `handle'

use "$MyPath/save/bycohort_welfare_collateral", clear
sum welfare_total_10 [w = num_mean] if inrange(age, 0, 80)
local m = r(mean)
sum welfare_total_10 [w = num_mean] if inrange(age, 0, 19)
local m1 = r(mean)
sum welfare_total_10 [w = num_mean] if inrange(age, 20, 39)
local m2 = r(mean)
sum welfare_total_10 [w = num_mean] if inrange(age, 40, 59)
local m3 = r(mean)
sum welfare_total_10 [w = num_mean] if inrange(age, 60, 80)
local m4 = r(mean)
post `postname' ("\enspace Borrowing constraints and collateral effects") (`m'-`m_baseline') (`m1'-`m1_baseline') (`m2'-`m2_baseline') (`m3'-`m3_baseline') (`m4'-`m4_baseline')

use "$MyPath/save/bycohort_welfare_secondorder", clear
sum welfare_total_2nd [w = num_mean] if inrange(age, 0, 80)
local m = r(mean)
sum welfare_total_2nd [w = num_mean] if inrange(age, 0, 19)
local m1 = r(mean)
sum welfare_total_2nd [w = num_mean] if inrange(age, 20, 39)
local m2 = r(mean)
sum welfare_total_2nd [w = num_mean] if inrange(age, 40, 59)
local m3 = r(mean)
sum welfare_total_2nd [w = num_mean] if inrange(age, 60, 80)
local m4 = r(mean)
post `postname' ("\enspace Second-order effects") (`m'-`m_baseline') (`m1'-`m1_baseline') (`m2'-`m2_baseline') (`m3'-`m3_baseline') (`m4'-`m4_baseline')

use "$MyPath/save/bycohort_welfare_untruncated", clear
sum welfare_total_90 [w = num_mean] if inrange(age, 0, 80)
local m = r(mean)
sum welfare_total_90 [w = num_mean] if inrange(age, 0, 19)
local m1 = r(mean)
sum welfare_total_90 [w = num_mean] if inrange(age, 20, 39)
local m2 = r(mean)
sum welfare_total_90 [w = num_mean] if inrange(age, 40, 59)
local m3 = r(mean)
sum welfare_total_90 [w = num_mean] if inrange(age, 60, 80)
local m4 = r(mean)
post `postname' ("\enspace Extrapolation") (`m'-`m_baseline') (`m1'-`m1_baseline') (`m2'-`m2_baseline') (`m3'-`m3_baseline') (`m4'-`m4_baseline')

use "$MyPath/save/bycohort_welfare_combine", clear
sum welfare_total_combine [w = num_mean]  if inrange(age, 0, 80)
local m = r(mean)
sum welfare_total_combine [w = num_mean]  if inrange(age, 0, 19)
local m1 = r(mean)
sum welfare_total_combine [w = num_mean] if inrange(age, 20, 39)
local m2 = r(mean)
sum welfare_total_combine [w = num_mean] if inrange(age, 40, 59)
local m3 = r(mean)
sum welfare_total_combine [w = num_mean] if inrange(age, 60, 80)
post `postname' ( "\noalign{\vskip 1.5mm} Combining all extensions") (`m') (`m1') (`m2') (`m3') (`m4')


* Display table
postclose `postname'
use `postfile', clear
tostring m m1 m2 m3 m4, replace force format(%3.1fc)
foreach v of varlist m*{
    replace `v' = "+" + `v' if inrange(_n, 2, 5)  & (substr(`v', 1, 1) != "-")
}
listtab label m m1 m2 m3 m4 using "$MyPath/Tables/Table3.tex", replace rstyle(tabular)

/***************************************************************************************************
Figure A13: Welfare gains across cohorts after combining all extensions
***************************************************************************************************/
use "$MyPath/save/bycohort_welfare_untruncated", clear
merge 1:1 age using "$MyPath/save/bycohort_welfare_baseline", nogen
merge 1:1 age using "$MyPath/save/bycohort_welfare_incomplete", nogen
merge 1:1 age using "$MyPath/save/bycohort_welfare_collateral", nogen
merge 1:1 age using "$MyPath/save/bycohort_welfare_secondorder", nogen
merge 1:1 age using "$MyPath/save/bycohort_welfare_combine", nogen
gen welfare_total_added = welfare_total + (welfare_incomplete1 - welfare_total) + (welfare_total_10 - welfare_total) + (welfare_total_2nd - welfare_total) + (welfare_total_90 - welfare_total)
gen age_alt = round(age / 3) * 3
collapse (mean) welfare_total* [w = num_mean], by(age_alt)

twoway ///
(line welfare_total age if inrange(age, 3, 80), color(black) lwidth(thick) ) ///
(line welfare_total_added age if inrange(age, 3, 80), color(black%75) lwidth(medthick) lpattern(longdash)) ///
(line welfare_total_combine age if inrange(age, 3, 80), color(black%50) lwidth(medthick) lpattern(shortdash)) ///
, yline(0, lpattern(solid) lwidth(thin) lcolor(black)) ///
ysize(4) xsize(6) graphregion(color(white) margin(l=0)) ///
xlabel(10[10]80, labsize(medlarge) grid glcolor(gs14) glwidth(vthin)) ///
ylabel(-50 "-50K" -25 "-25K" 0 "0K" 25 "25K" 50 "50K", labsize(medlarge) grid glcolor(gs14) glwidth(vthin) angle(0)) ///
yscale(range(-50 50)) ///
ytitle("Welfare gain", size(medlarge))  xtitle("Initial age", size(medlarge)) ///
legend(order(1 "Baseline" 2 "Adding extensions linearly" 3 "Combining extensions together") cols(1) size(medlarge) symysize(6) symxsize(8) region(lwidth(vvthin)))  
graph export "$MyPath/Figures/FigureA13.$suffix", replace

